package com.lx.huimailf.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.internal.ObjectConstructor;
import com.lx.huimailf.R;
import com.lx.huimailf.adapter.OrderManagerAdapter1;
import com.lx.huimailf.configs.Config;
import com.lx.huimailf.weight.MyListView;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class MyCustomerActivity extends Activity implements View.OnClickListener {
    private TextView number, first, left, right, all,point,zong;
    private MyListView lv;
    private RelativeLayout fanhui;
    private String custid;
    private PoiAdapter madapter;
    private String s;
    JSONArray jsonArray;
    int VIEW_COUNT = 6;//每页显示个数
    int index = 0;//用于显示页号的索引
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fresco.initialize(this);
        setContentView(R.layout.activity_my_customer);
        SharedPreferences sp = getSharedPreferences("user", Context.MODE_PRIVATE);
        custid = sp.getString("custid", "-11111");
        initView();
        getInfo();
        getCount();
    }

    private void initView() {
        fanhui = (RelativeLayout) findViewById(R.id.fanhui);
        lv = (MyListView) findViewById(R.id.listView);
        number = (TextView) findViewById(R.id.number);
        first = (TextView) findViewById(R.id.first);
        left = (TextView) findViewById(R.id.left);
        right = (TextView) findViewById(R.id.right);
        all = (TextView) findViewById(R.id.all);
        point=(TextView)findViewById(R.id.point);
        zong=(TextView)findViewById(R.id.zong);
        left.setOnClickListener(this);
        right.setOnClickListener(this);
        first.setOnClickListener(this);
        fanhui.setOnClickListener(this);
        //checkButton();
    }
    private  void getCount(){
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("linkerid", custid);
        Gson gson = new Gson();
        String str = gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url + "customer/searchCustomerCount.do")
                .addParams("data", str)
                .addParams("mobile", "true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("客户数量==" + response);
                        number.setText(response);
                    }
                });
    }
    private void getInfo() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("linkerid", custid);
        map.put("page", "1");
        map.put("rows", "1000000");
        Gson gson = new Gson();
        String str = gson.toJson(map);
        OkHttpUtils
                .post()
                .url(Config.url + "customer/searchCustomer.do")
                .addParams("data", str)
                .addParams("mobile", "true")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.print("客户信息==" + response);
                        ArrayList<Map<String, Object>> mList = new ArrayList<Map<String, Object>>();
                        try {
                            jsonArray = new JSONArray(response);
                            s=String .valueOf(jsonArray.length()/VIEW_COUNT+1);
                            all.setText("共"+s+"页");
                            zong.setText(s);
                            checkButton();
                            for (int i = 0; i < jsonArray.length(); i++) {
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("name", jsonArray.getJSONObject(i).getString("name"));
                                map.put("phone", jsonArray.getJSONObject(i).getString("phone"));
                                map.put("createtime", jsonArray.getJSONObject(i).getString("createtime"));
                                map.put("picname", jsonArray.getJSONObject(i).getString("picname"));
                                map.put("picsrc", jsonArray.getJSONObject(i).getString("picsrc"));
                                map.put("count", jsonArray.getJSONObject(i).getString("count"));
                                map.put("money", jsonArray.getJSONObject(i).getString("money"));
                                mList.add(map);
                            }
                            madapter = new PoiAdapter(MyCustomerActivity.this, mList);
                            lv.setAdapter(madapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fanhui:
               MyCustomerActivity.this.finish();
                break;
            case R.id.first:
                index=0;
                point.setText("1");
                madapter.notifyDataSetChanged();
                checkButton();
                break;
            case R.id.left:
                leftView();
                checkButton();
                break;
            case R.id.right:
                    rightView();
                    checkButton();
                break;
        }
    }
    private void checkButton(){

        if(index <= 0) {
            left.setEnabled(false);
            if (!s.equals("1")){
                right.setEnabled(true);
            }else{
                right.setEnabled(false);
            }

        }else if(jsonArray.length()-index * VIEW_COUNT <= VIEW_COUNT){
           right.setEnabled(false);
            left.setEnabled(true);
        }else{
           left.setEnabled(true);
           right.setEnabled(true);
        }
    }
    private void rightView() {
        index++;
        String num_add=Integer.valueOf(point.getText().toString())+1+"";
        point.setText(num_add);
        madapter.notifyDataSetChanged();

    }

    private void leftView() {
        index--;
        String num_reduce=Integer.valueOf(point.getText().toString())-1+"";
        point.setText(num_reduce);
       madapter.notifyDataSetChanged();

    }

    public class PoiAdapter extends BaseAdapter {
        List<Map<String, Object>> Lists;
        private Context context;

        public PoiAdapter(Context context, List<Map<String, Object>> Lists) {
            super();
            this.context = context;
            this.Lists = Lists;
        }

        @Override
        public int getCount() {
            int ori = VIEW_COUNT*index;
            if(Lists.size()-ori<VIEW_COUNT){
                return Lists.size()-ori;
            }else{
                return VIEW_COUNT;
            }
        }

        @Override
        public Object getItem(int position) {
            return Lists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("InflateParams")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.customer, null);
                holder.logo = (SimpleDraweeView) convertView.findViewById(R.id.logo);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.phone = (TextView) convertView.findViewById(R.id.phone);
                holder.time = (TextView) convertView.findViewById(R.id.time);
                holder.dingdan = (TextView) convertView.findViewById(R.id.dingdan);
                holder.jine = (TextView) convertView.findViewById(R.id.jine);
                convertView.setTag(holder);
            } else {
                // 取出holder
                holder = (ViewHolder) convertView.getTag();
            }
           Uri uri =Uri.parse(Config.url +  Lists.get(position+index*VIEW_COUNT).get("picsrc")+"/" + Lists.get(position+index*VIEW_COUNT).get("picname") + "");
           holder.logo.setImageURI(uri);
            Date date = new Date(Long.valueOf(Lists.get(position+index*VIEW_COUNT).get("createtime").toString()));
            SimpleDateFormat format;
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            holder.time.setText(format.format(date));
            holder.phone.setText(Lists.get(position+index*VIEW_COUNT).get("phone").toString());
            holder.name.setText(Lists.get(position+index*VIEW_COUNT).get("name").toString());
            if (Lists.get(position+index*VIEW_COUNT).get("count").toString().equals("null")) {
                holder.dingdan.setText("0" + "笔" + "");
            } else {
                holder.dingdan.setText(Lists.get(position+index*VIEW_COUNT).get("count") + "笔" + "");
            }
            if (Lists.get(position+index*VIEW_COUNT).get("money").toString().equals("null")) {
                holder.jine.setText("￥" + "0" + "");
            } else {
                holder.jine.setText("￥" + Lists.get(position+index*VIEW_COUNT).get("money") + "");
            }

            return convertView;
        }

        public class ViewHolder {
            ImageView logo;
            TextView name;
            TextView phone;
            TextView time, dingdan, jine;

        }

    }
}
